extends Control

# 音效资源预加载
const CARD_PLAY_SOUND = preload("res://assets/audio/card_play.wav")
const END_TURN_SOUND = preload("res://assets/audio/end_turn.wav")

# UI组件引用
@onready var game_ui: Control = $GameUI
@onready var menu_overlay: Control = $MenuOverlay

# 玩家信息UI
@onready var player_health_label: Label = $GameUI/BottomPanel/PlayerInfo/PlayerHealthLabel
@onready var player_mana_label: Label = $GameUI/BottomPanel/PlayerInfo/PlayerManaLabel
@onready var end_turn_button: Button = $GameUI/BottomPanel/PlayerInfo/EndTurnButton

# AI信息UI
@onready var ai_health_label: Label = $GameUI/TopPanel/AIInfo/AIHealthLabel
@onready var ai_mana_label: Label = $GameUI/TopPanel/AIInfo/AIManaLabel
@onready var turn_label: Label = $GameUI/TopPanel/AIInfo/TurnLabel

# 战场UI
@onready var player_board_container: HBoxContainer = $GameUI/PlayerBoard/PlayerBoardContainer
@onready var ai_board_container: HBoxContainer = $GameUI/AIBoard/AIBoardContainer
@onready var player_hand_container: HBoxContainer = $GameUI/BottomPanel/PlayerHandContainer

# 游戏日志
@onready var game_log: RichTextLabel = $GameUI/SidePanel/GameLogScroll/GameLog

# 菜单按钮
@onready var start_button: Button = $MenuOverlay/MenuPanel/MenuVBox/StartButton
@onready var settings_button: Button = $MenuOverlay/MenuPanel/MenuVBox/SettingsButton
@onready var quit_button: Button = $MenuOverlay/MenuPanel/MenuVBox/QuitButton

# 设置界面
@onready var settings_overlay: Control = $SettingsOverlay
@onready var master_volume_slider: HSlider = $SettingsOverlay/SettingsPanel/SettingsVBox/AudioSection/MasterVolumeContainer/MasterVolumeSlider
@onready var master_volume_value: Label = $SettingsOverlay/SettingsPanel/SettingsVBox/AudioSection/MasterVolumeContainer/MasterVolumeValue
@onready var sfx_volume_slider: HSlider = $SettingsOverlay/SettingsPanel/SettingsVBox/AudioSection/SFXVolumeContainer/SFXVolumeSlider
@onready var sfx_volume_value: Label = $SettingsOverlay/SettingsPanel/SettingsVBox/AudioSection/SFXVolumeContainer/SFXVolumeValue
@onready var auto_end_turn_checkbox: CheckBox = $SettingsOverlay/SettingsPanel/SettingsVBox/GameplaySection/AutoEndTurnContainer/AutoEndTurnCheckBox
@onready var show_tooltips_checkbox: CheckBox = $SettingsOverlay/SettingsPanel/SettingsVBox/GameplaySection/ShowTooltipsContainer/ShowTooltipsCheckBox
@onready var reset_button: Button = $SettingsOverlay/SettingsPanel/SettingsVBox/ButtonsContainer/ResetButton
@onready var back_button: Button = $SettingsOverlay/SettingsPanel/SettingsVBox/ButtonsContainer/BackButton

# 卡牌提示框
@onready var card_tooltip: Control = $CardTooltip

# 游戏结束页面
@onready var game_over_screen: Control = $GameOverScreen

# 背景音乐播放器
@onready var background_music_player: AudioStreamPlayer = $BackgroundMusicPlayer

# 音效播放器
@onready var sound_effect_player: AudioStreamPlayer = $SoundEffectPlayer

# 游戏状态
var is_game_active: bool = false
var selected_card: Control = null
var is_dragging_card: bool = false

# 设置数据
var game_settings = {
	"master_volume": 80,
	"sfx_volume": 70,
	"sound_effect_volume": 80,  # 音效音量设置
	"auto_end_turn": false,
	"show_tooltips": true
}

# 设置文件路径
const SETTINGS_FILE_PATH = "user://game_settings.save"

func _ready():
	print("🚀🚀🚀 MAIN SCRIPT _ready() 函数开始执行 🚀🚀🚀")
	print("🚀🚀🚀 Main: _ready函数被调用，开始初始化 🚀🚀🚀")
	print("🚀🚀🚀 这是Main节点的_ready函数！🚀🚀🚀")
	
	# 将节点添加到main组，方便其他脚本找到
	add_to_group("main")
	print("Main: 节点已添加到main组")
	
	# 连接菜单按钮信号
	start_button.pressed.connect(_on_start_button_pressed)
	settings_button.pressed.connect(_on_settings_button_pressed)
	quit_button.pressed.connect(_on_quit_button_pressed)
	
	# 设置全局输入处理
	set_process_unhandled_input(true)
	
	# 连接游戏按钮信号
	end_turn_button.pressed.connect(_on_end_turn_button_pressed)
	
	# 连接GameManager信号
	if GameManager:
		GameManager.game_started.connect(_on_game_started)
		GameManager.turn_changed.connect(_on_turn_changed)
		GameManager.game_ended.connect(_on_game_ended)
		GameManager.health_changed.connect(_on_health_changed)
		GameManager.mana_changed.connect(_on_mana_changed)
		GameManager.card_played.connect(_on_card_played)
		GameManager.unit_attacked.connect(_on_unit_attacked)
		GameManager.hand_updated.connect(_on_hand_updated)  # 手牌变化时智能更新显示
		GameManager.board_updated.connect(_on_board_updated)  # 战场变化时更新显示
		print("Main: 已连接hand_updated信号到_on_hand_updated")
		print("Main: 已连接board_updated信号到_on_board_updated")
	
	# 连接卡牌提示框相关信号
	_connect_card_tooltip_signals()
	
	# 连接游戏结束页面信号
	if game_over_screen:
		print("Main: 找到GameOverScreen节点: ", game_over_screen.name)
		game_over_screen.play_again_requested.connect(_on_play_again_requested)
		game_over_screen.main_menu_requested.connect(_on_main_menu_requested)
		print("Main: GameOverScreen信号连接完成")
	else:
		print("Main: 警告 - GameOverScreen节点未找到!")
	
	# 测试提示框节点
	if card_tooltip:
		print("Main: 提示框节点已找到: ", card_tooltip.name)
		print("Main: 提示框初始可见性: ", card_tooltip.visible)
	else:
		print("Main: 警告 - 提示框节点未找到!")
	
	# 简化测试 - 直接检查提示框状态
	print("Main: 提示框测试 - 节点状态检查")
	print("Main: card_tooltip存在: ", card_tooltip != null)
	if card_tooltip:
		print("Main: 提示框节点名称: ", card_tooltip.name)
		print("Main: 提示框可见性: ", card_tooltip.visible)
	print("Main: 按H键可以测试提示框显示功能")
	
	# 立即执行提示框测试
	print("Main: 立即执行提示框测试")
	test_tooltip_display()
	
	# 加载直接提示框测试脚本
	var direct_test_script = load("res://direct_tooltip_test.gd")
	if direct_test_script:
		var direct_test_instance = direct_test_script.new()
		add_child(direct_test_instance)
		print("Main: 直接提示框测试脚本加载成功")
	
	# 延迟执行自动提示框测试
	call_deferred("auto_test_tooltip_delayed")
	
	# 额外延迟8秒后再次测试提示框功能
	get_tree().create_timer(8.0).timeout.connect(test_tooltip_display)
	
	# 加载提示框测试脚本
	var tooltip_test_script = load("res://tooltip_test.gd")
	if tooltip_test_script:
		var tooltip_test_instance = tooltip_test_script.new()
		add_child(tooltip_test_instance)
		print("提示框测试脚本加载成功")
	
	# 加载简化鼠标悬停测试脚本
	var simple_hover_test_script = load("res://scripts/simple_hover_test.gd")
	if simple_hover_test_script:
		var simple_hover_test_instance = simple_hover_test_script.new()
		add_child(simple_hover_test_instance)
		print("Main: 简化鼠标悬停测试脚本加载成功")
	else:
		print("Main: 简化鼠标悬停测试脚本加载失败")
	
	# 设置手牌容器的间距和鼠标过滤器
	if player_hand_container:
		player_hand_container.add_theme_constant_override("separation", 10)
		# 关键修复：设置鼠标过滤器为PASS，允许鼠标事件传递给子节点（卡牌）
		player_hand_container.mouse_filter = Control.MOUSE_FILTER_PASS
		print("Main: 设置手牌容器间距为 10，鼠标过滤器为PASS")
	
	# 调试脚本已不再需要，卡牌点击功能已修复
	#var card_click_debug = preload("res://card_click_debug.gd").new()
	#add_child(card_click_debug)
	
	# 深度信号调试脚本也不再需要
	#var signal_debug = preload("res://signal_debug_test.gd").new()
	#add_child(signal_debug)
	
	# 卡牌点击功能已修复 - 修复了Card.tscn中所有子节点的mouse_filter设置
	
	# 鼠标悬停测试脚本已集成到简化测试中
	
	# 初始化设置系统
	print("Main: 准备初始化设置系统...")
	initialize_settings()
	print("Main: 设置系统初始化完成")
	
	# 初始化背景音乐
	print("Main: 准备初始化背景音乐...")
	await initialize_background_music()
	print("Main: 背景音乐初始化流程完成")
	
	# 显示开始菜单（而不是自动启动游戏）
	print("Main: 显示开始菜单")
	show_menu()

func _input(event):
	"""处理全局输入事件"""
	if event is InputEventKey and event.pressed:
		match event.keycode:
			KEY_T:
				print("Main: 按下T键，测试鼠标悬停功能")
				test_mouse_hover_manually()
			KEY_U:
				print("按下U键，开始测试提示框...")
				test_tooltip_simple()
			KEY_H:
				print("Main: 按下H键，测试提示框显示")
				test_tooltip_display()
			KEY_SPACE:
				# 空格键结束回合
				if is_game_active and GameManager.current_state == GameManager.GameState.PLAYER_TURN:
					GameManager.end_turn()
			KEY_ESCAPE:
				# ESC键处理菜单和设置界面的切换
				if settings_overlay.visible:
					# 如果设置界面打开，则关闭设置界面
					hide_settings()
				elif is_game_active:
					# 如果游戏进行中，显示菜单
					show_menu()
				elif menu_overlay.visible:
					# 如果菜单打开，隐藏菜单（返回游戏）
					hide_menu()
			KEY_R:
				# R键重新开始游戏
				if event.ctrl_pressed:
					start_new_game()
			KEY_M:
				# M键切换背景音乐播放/暂停
				print("Main: 🎵 M键被按下，切换背景音乐状态")
				if background_music_player:
					print("Main: 当前播放状态: playing=", background_music_player.playing, ", paused=", background_music_player.stream_paused)
					# 检查循环设置
					if background_music_player.stream:
						if background_music_player.stream is AudioStreamMP3:
							print("Main: 🔄 当前循环设置: ", background_music_player.stream.loop)
						else:
							print("Main: ⚠️ 音频流类型: ", background_music_player.stream.get_class())
					else:
						print("Main: ❌ 没有音频流")
					
					if background_music_player.playing and not background_music_player.stream_paused:
						pause_background_music()
					else:
						resume_background_music()
				else:
					print("Main: ❌ 背景音乐播放器未找到")
			KEY_N:
				# N键停止背景音乐
				stop_background_music()
			KEY_P:
				# P键播放背景音乐
				play_background_music()

func test_tooltip_simple():
	"""简单的提示框测试"""
	print("=== 开始简单提示框测试 ===")
	
	# 检查提示框节点
	if not card_tooltip:
		print("❌ CardTooltip节点未找到")
		return
	
	print("✅ 找到CardTooltip节点")
	print("  - 节点类型: ", card_tooltip.get_class())
	print("  - 初始可见性: ", card_tooltip.visible)
	print("  - 初始透明度: ", card_tooltip.modulate.a)
	
	# 检查手牌容器和卡牌
	if not player_hand_container:
		print("❌ PlayerHandContainer未找到")
		return
	
	var cards = player_hand_container.get_children()
	if cards.size() == 0:
		print("❌ 没有找到卡牌")
		return
	
	var first_card = cards[0]
	print("✅ 找到第一张卡牌: ", first_card.name)
	print("  - 卡牌类型: ", first_card.get_class())
	print("  - 卡牌位置: ", first_card.global_position)
	print("  - 卡牌大小: ", first_card.size)
	
	# 测试显示提示框
	print("\n📍 显示提示框...")
	var mouse_pos = Vector2(400, 300)
	
	if card_tooltip.has_method("show_tooltip"):
		card_tooltip.show_tooltip(first_card, mouse_pos)
		print("✅ show_tooltip方法调用成功")
		
		# 等待0.5秒检查状态
		await get_tree().create_timer(0.5).timeout
		print("  - 显示后可见性: ", card_tooltip.visible)
		print("  - 显示后透明度: ", card_tooltip.modulate.a)
		print("  - 显示后位置: ", card_tooltip.position)
		
		# 等待3秒后隐藏
		await get_tree().create_timer(3.0).timeout
		print("\n📍 隐藏提示框...")
		
		if card_tooltip.has_method("hide_tooltip"):
			card_tooltip.hide_tooltip()
			print("✅ hide_tooltip方法调用成功")
			
			# 等待0.5秒检查隐藏状态
			await get_tree().create_timer(0.5).timeout
			print("  - 隐藏后可见性: ", card_tooltip.visible)
			print("  - 隐藏后透明度: ", card_tooltip.modulate.a)
		else:
			print("❌ hide_tooltip方法不存在")
	else:
		print("❌ show_tooltip方法不存在")
	
	print("=== 简单提示框测试结束 ===")

func test_tooltip_display():
	"""测试提示框显示功能"""
	print("Main: 开始测试提示框显示")
	write_test_log("开始测试提示框显示")
	
	if not card_tooltip:
		print("Main: 提示框节点未找到")
		write_test_log("错误: 提示框节点未找到")
		return
	
	write_test_log("提示框节点已找到: " + card_tooltip.name)
	
	if not player_hand_container or player_hand_container.get_child_count() == 0:
		print("Main: 没有可用的卡牌")
		write_test_log("错误: 没有可用的卡牌")
		return
	
	var test_card = player_hand_container.get_child(0)
	print("Main: 使用卡牌进行测试: ", test_card.name)
	write_test_log("使用卡牌进行测试: " + test_card.name)
	
	# 直接显示提示框
	print("Main: 显示提示框...")
	write_test_log("显示提示框...")
	card_tooltip.show_tooltip(test_card, Vector2(500, 400))
	write_test_log("提示框可见性: " + str(card_tooltip.visible))
	
	# 等待3秒后隐藏
	await get_tree().create_timer(3.0).timeout
	print("Main: 隐藏提示框...")
	write_test_log("隐藏提示框...")
	card_tooltip.hide_tooltip()
	write_test_log("测试完成")

func auto_test_tooltip_delayed():
	"""延迟执行的自动提示框测试"""
	print("Main: 准备执行延迟提示框测试")
	# 等待2秒确保游戏完全初始化
	await get_tree().create_timer(2.0).timeout
	print("Main: 开始执行延迟提示框测试")
	test_tooltip_display()

func auto_test_tooltip():
	"""自动测试提示框功能"""
	print("Main: 开始自动提示框测试")
	print("Main: card_tooltip节点状态: ", card_tooltip)
	print("Main: player_hand_container节点状态: ", player_hand_container)
	
	# 直接使用print而不是write_test_log，避免文件写入问题
	print("=== 自动提示框测试开始 ===")
	
	# 等待一帧确保所有节点都已初始化
	await get_tree().process_frame
	print("Main: 等待一帧后继续测试")
	
	# 检查提示框节点
	if not card_tooltip:
		print("Main: 自动测试 - 提示框节点未找到")
		print("错误: 提示框节点未找到")
		return
	
	print("提示框节点已找到: " + card_tooltip.name)
	print("提示框初始可见性: " + str(card_tooltip.visible))
	
	# 检查手牌
	if not player_hand_container:
		print("错误: 手牌容器未找到")
		return
	
	print("手牌容器子节点数量: " + str(player_hand_container.get_child_count()))
	
	if player_hand_container.get_child_count() > 0:
		var test_card = player_hand_container.get_child(0)
		print("测试卡牌: " + test_card.name)
		print("测试卡牌类型: " + str(test_card.get_class()))
		
		# 检查卡牌是否有必要的属性
		if test_card.has_method("get") and test_card.get("card_name"):
			print("卡牌名称: " + str(test_card.card_name))
		else:
			print("警告: 卡牌缺少card_name属性")
		
		# 测试显示提示框
		print("开始显示提示框...")
		card_tooltip.show_tooltip(test_card, Vector2(400, 300))
		
		# 等待一帧检查结果
		await get_tree().process_frame
		print("显示后提示框可见性: " + str(card_tooltip.visible))
		print("提示框透明度: " + str(card_tooltip.modulate.a))
		
		# 等待2秒
		await get_tree().create_timer(2.0).timeout
		
		# 隐藏提示框
		print("开始隐藏提示框...")
		card_tooltip.hide_tooltip()
		
		await get_tree().process_frame
		print("隐藏后提示框可见性: " + str(card_tooltip.visible))
	else:
		print("错误: 没有可用的卡牌进行测试")
	
	print("=== 自动提示框测试结束 ===")

func write_test_log(message: String):
	"""写入测试日志到文件"""
	var file = FileAccess.open("res://tooltip_test.log", FileAccess.WRITE)
	if file:
		file.store_line(Time.get_datetime_string_from_system() + ": " + message)
		file.close()
	else:
		# 如果无法写入res://，尝试写入到用户目录
		file = FileAccess.open("user://tooltip_test.log", FileAccess.WRITE)
		if file:
			file.store_line(Time.get_datetime_string_from_system() + ": " + message)
			file.close()

func test_mouse_hover_manually():
	"""手动测试鼠标悬停功能"""
	print("Main: 开始手动测试鼠标悬停功能")
	
	if not player_hand_container:
		print("Main: ❌ 手牌容器不存在")
		return
	
	var cards = player_hand_container.get_children()
	if cards.size() == 0:
		print("Main: ❌ 没有找到卡牌")
		return
	
	var first_card = cards[0]
	print("Main: 找到第一张卡牌: ", first_card.name)
	print("Main: 卡牌名称: ", first_card.card_name if first_card.has_method("get") and first_card.get("card_name") else "未知")
	
	# 检查提示框是否存在
	if not card_tooltip:
		print("Main: ❌ 提示框不存在")
		return
	
	print("Main: ✅ 提示框存在，开始测试...")
	
	# 直接调用提示框显示方法
	print("Main: 直接显示提示框...")
	var mouse_pos = Vector2(500, 300)  # 屏幕中央位置
	card_tooltip.show_tooltip(first_card, mouse_pos)
	print("Main: 提示框显示命令已发送")
	
	# 等待3秒后隐藏提示框
	await get_tree().create_timer(3.0).timeout
	print("Main: 隐藏提示框...")
	card_tooltip.hide_tooltip()
	print("Main: 提示框隐藏命令已发送")
	
	# 再等待1秒后通过信号方式测试
	await get_tree().create_timer(1.0).timeout
	print("Main: 通过信号方式测试...")
	_on_card_mouse_entered(first_card)
	
	await get_tree().create_timer(2.0).timeout
	_on_card_mouse_exited(first_card)
	# var diagnosis_script = preload("res://scripts/CardClickDiagnosis.gd")
	# var diagnosis_node = Control.new()
	# diagnosis_node.set_script(diagnosis_script)
	# add_child(diagnosis_node)
	
	# 法术卡手牌保留测试脚本（已完成测试）
	# var spell_test_script = load("res://test_spell_hand_retention.gd").new()
	# add_child(spell_test_script)
	
	# 卡牌信号连接测试脚本（已完成测试）
	# var signal_test = preload("res://card_signal_test.gd").new()
	# add_child(signal_test)
	
	# 手牌状态测试脚本（已完成验证）
	# var hand_state_test = preload("res://hand_card_state_test.gd").new()
	# add_child(hand_state_test)
	
	# 点击验证测试已完成
	# var click_test = preload("res://click_verification_test.gd").new()
	# add_child(click_test)
	
	# 伤害测试脚本已移除，改用GameManager中的自动测试
	# var damage_test = preload("res://damage_test.gd").new()
	# add_child(damage_test)
	
	# 调试信息将在游戏开始后执行
	
	# 初始显示菜单
	show_menu()

# 全局输入检测，用于调试
func _unhandled_input(event):
	if event is InputEventMouseButton:
		print("🖱️ 全局鼠标事件检测:")
		print("  - 按钮: ", event.button_index)
		print("  - 是否按下: ", event.pressed)
		print("  - 位置: ", event.position)
		print("  - 全局位置: ", event.global_position)
	
	# 添加键盘快捷键功能
	if event is InputEventKey and event.pressed:
		if event.keycode == KEY_H:
			print("🔧 检测到H键按下，开始测试提示框功能")
			test_tooltip_display()
		elif event.keycode == KEY_V:
			# 测试胜利界面 (V键)
			print("🏆 检测到V键按下，测试胜利界面")
			_test_victory()
		elif event.keycode == KEY_D:
			# 测试失败界面 (D键)
			print("💀 检测到D键按下，测试失败界面")
			_test_defeat()
		elif event.keycode == KEY_G:
			# 通过GameManager触发胜利测试 (G键)
			print("🎮 检测到G键按下，通过GameManager触发胜利测试")
			if GameManager:
				GameManager.test_trigger_victory()
			else:
				print("❌ GameManager未找到")
		elif event.keycode == KEY_F:
			# 通过GameManager触发失败测试 (F键)
			print("🎮 检测到F键按下，通过GameManager触发失败测试")
			if GameManager:
				GameManager.test_trigger_defeat()
			else:
				print("❌ GameManager未找到")
		elif event.keycode == KEY_EQUAL or event.keycode == KEY_KP_ADD:
			# 增加音效音量（+键或数字键盘+）
			adjust_sound_effect_volume(10)
		elif event.keycode == KEY_MINUS or event.keycode == KEY_KP_SUBTRACT:
			# 减少音效音量（-键或数字键盘-）
			adjust_sound_effect_volume(-10)

func show_menu():
	"""显示主菜单"""
	menu_overlay.visible = true
	game_ui.visible = false
	is_game_active = false

func hide_menu():
	"""隐藏主菜单"""
	menu_overlay.visible = false
	game_ui.visible = true

func start_new_game():
	"""开始新游戏"""
	hide_menu()
	is_game_active = true
	
	# 清空UI
	clear_all_containers()
	
	# 初始化游戏日志
	game_log.clear()
	log_message("[color=yellow]游戏开始！[/color]")
	
	# 启动GameManager
	if GameManager:
		GameManager.initialize_game()
	else:
		log_message("[color=red]错误：GameManager未找到！[/color]")

func clear_all_containers():
	"""清空所有容器"""
	# 清空手牌容器
	for child in player_hand_container.get_children():
		child.queue_free()
	
	# 清空战场容器
	for child in player_board_container.get_children():
		child.queue_free()
	
	for child in ai_board_container.get_children():
		child.queue_free()

func _on_hand_updated():
	"""智能处理手牌更新 - 只在必要时重建，否则只添加新卡牌"""
	if not GameManager:
		print("Main: GameManager未找到，无法更新手牌")
		return
	
	var current_hand_size = GameManager.player_hand.size()
	var current_ui_size = player_hand_container.get_child_count()
	
	print("Main: 手牌更新 - 数据中手牌数量: ", current_hand_size, ", UI中卡牌数量: ", current_ui_size)
	
	# 先清理UI中已经不在数据手牌中的卡牌（比如被打出的法术卡）
	var ui_cards_to_remove = []
	for child in player_hand_container.get_children():
		if child not in GameManager.player_hand:
			ui_cards_to_remove.append(child)
			print("Main: 发现需要从UI移除的卡牌: ", child.card_name)
	
	# 移除这些卡牌
	for card in ui_cards_to_remove:
		player_hand_container.remove_child(card)
		print("Main: 从UI移除卡牌: ", card.card_name)
	
	# 重新计算UI中的卡牌数量
	current_ui_size = player_hand_container.get_child_count()
	
	# 如果数据中的手牌数量比UI中的多，说明抽到了新牌，只需添加新牌
	if current_hand_size > current_ui_size:
		# 添加新抽取的卡牌
		for i in range(current_ui_size, current_hand_size):
			var card = GameManager.player_hand[i]
			if card:
				print("Main: 添加新卡牌: ", card.card_name)
				add_card_to_hand(card)
	# 如果UI中的卡牌数量仍然比数据中的多，需要重建
	elif current_ui_size > current_hand_size:
		rebuild_player_hand()
	# 如果数量相等，只需要更新可打出状态
	else:
		update_playable_cards_ui()

func rebuild_player_hand():
	"""完全重建玩家手牌显示（仅在必要时使用）"""
	if not GameManager:
		print("Main: GameManager未找到，无法重建手牌")
		return
	
	print("Main: 开始重建玩家手牌，当前手牌数量: ", GameManager.player_hand.size())
	
	# 清空当前手牌显示
	for child in player_hand_container.get_children():
		player_hand_container.remove_child(child)
		child.queue_free()
	
	# 添加新的手牌
	for i in range(GameManager.player_hand.size()):
		var card = GameManager.player_hand[i]
		if card:
			add_card_to_hand(card)
		else:
			print("Main: 手牌 ", i+1, " 为空")
	
	print("Main: 手牌重建完成，容器中卡牌数量: ", player_hand_container.get_child_count())

func _on_board_updated():
	"""处理战场更新信号"""
	print("Main: 收到战场更新信号，开始更新战场显示")
	update_player_board()
	update_ai_board()

func update_playable_cards_ui():
	"""只更新手牌中卡牌的可打出状态，不重建UI"""
	if not GameManager:
		return
	
	# 遍历手牌容器中的卡牌，更新其可打出状态
	for child in player_hand_container.get_children():
		if child.has_method("set_playable"):
			var can_play = GameManager.can_play_card(child, GameManager.PlayerType.PLAYER)
			child.set_playable(can_play)

func add_card_to_hand(card: Control):
	"""将卡牌添加到手牌显示"""
	if not card:
		print("Main: add_card_to_hand - 卡牌为空")
		return
	
	# 如果卡牌已经有父节点，先移除
	if card.get_parent():
		card.get_parent().remove_child(card)
	
	# 设置卡牌尺寸和可见性
	card.custom_minimum_size = Vector2(120, 160)  # 设置卡牌最小尺寸
	card.size = Vector2(120, 160)  # 设置卡牌尺寸
	card.visible = true  # 确保卡牌可见
	card.z_index = 1  # 确保卡牌在正确层级
	card.modulate.a = 1.0  # 确保卡牌不透明
	
	# 设置布局标志，让HBoxContainer正确布局
	card.size_flags_horizontal = Control.SIZE_SHRINK_CENTER
	card.size_flags_vertical = Control.SIZE_SHRINK_CENTER
	
	# 设置卡牌父节点
	player_hand_container.add_child(card)
	
	# 强制刷新布局
	player_hand_container.queue_sort()
	player_hand_container.notification(NOTIFICATION_RESIZED)
	# 使用call_deferred来延迟执行布局检查
	call_deferred("_check_card_layout", card)


func _check_card_layout(card: Control):
	"""检查卡牌布局（延迟执行）"""
	# 检查卡牌是否仍然有效
	if is_instance_valid(card):
		# 手动设置卡牌位置
		for i in range(player_hand_container.get_child_count()):
			var child = player_hand_container.get_child(i)
			child.position.x = i * 130  # 每张卡牌间隔130像素
			child.position.y = 0
	else:
		print("Main: 警告 - 卡牌对象已被释放")
	
	# 设置卡牌状态
	if is_instance_valid(card):
		card.is_in_hand = true
		card.is_on_board = false
	else:
		return  # 如果卡牌对象无效，直接返回
	
	# 连接手牌卡牌信号
	connect_hand_card_signals(card)


func update_player_board():
	"""更新玩家战场显示"""
	if not GameManager:
		return
	
	print("Main update_player_board: 开始更新玩家战场")
	print("Main update_player_board: GameManager.player_board 数量: ", GameManager.player_board.size())
	
	# 清空当前战场显示（只移除，不销毁）
	for child in player_board_container.get_children():
		player_board_container.remove_child(child)
	
	# 添加战场单位
	for i in range(GameManager.player_board.size()):
		var card = GameManager.player_board[i]
		if card and is_instance_valid(card):
			print("Main update_player_board: 添加卡牌 ", i, ": ", card.card_name)
			add_card_to_board(card, true)
		else:
			print("Main update_player_board: 跳过无效卡牌 ", i)
	
	print("Main update_player_board: 更新完成")

func update_ai_board():
	"""更新AI战场显示"""
	if not GameManager:
		return
	
	print("Main update_ai_board: 开始更新AI战场")
	print("Main update_ai_board: GameManager.ai_board 数量: ", GameManager.ai_board.size())
	
	# 清空当前AI战场显示（只移除，不销毁）
	for child in ai_board_container.get_children():
		ai_board_container.remove_child(child)
	
	# 添加AI战场单位
	for i in range(GameManager.ai_board.size()):
		var card = GameManager.ai_board[i]
		if card and is_instance_valid(card):
			print("Main update_ai_board: 添加卡牌 ", i, ": ", card.card_name)
			add_card_to_board(card, false)
		else:
			print("Main update_ai_board: 跳过无效卡牌 ", i)
	
	print("Main update_ai_board: 更新完成")

func clear_player_board():
	"""清空玩家战场"""
	if not GameManager:
		print("Main clear_player_board: GameManager不存在")
		return
	
	print("Main clear_player_board: 调用GameManager清空战场")
	# 调用GameManager的统一清空接口
	GameManager.clear_player_board()

func add_card_to_board(card: Control, is_player: bool):
	"""将卡牌添加到战场显示"""
	if not card:
		print("Main add_card_to_board: 卡牌为空，无法添加")
		return
	
	var container = player_board_container if is_player else ai_board_container
	var player_name = "玩家" if is_player else "AI"
	
	print("Main add_card_to_board: 添加", card.card_name, "到", player_name, "战场")
	print("Main add_card_to_board: 战场容器当前子节点数量: ", container.get_child_count())
	
	# 如果卡牌已经有父节点，先移除
	if card.get_parent():
		print("Main add_card_to_board: 从父节点移除卡牌: ", card.get_parent().name)
		card.get_parent().remove_child(card)
	
	# 添加到战场容器
	container.add_child(card)
	
	# 设置卡牌状态
	card.is_in_hand = false
	card.is_on_board = true
	
	# 确保卡牌可见
	card.visible = true
	card.modulate.a = 1.0
	
	# 设置布局属性，让HBoxContainer正确排列
	card.size_flags_horizontal = Control.SIZE_SHRINK_CENTER
	card.size_flags_vertical = Control.SIZE_SHRINK_CENTER
	
	# 重置位置和缩放，让容器自动布局
	card.position = Vector2.ZERO
	card.scale = Vector2(0.8, 0.8)  # 战场卡牌稍小一些
	
	# 强制刷新容器布局
	container.queue_sort()
	container.notification(NOTIFICATION_RESIZED)
	
	print("Main add_card_to_board: 添加完成，战场容器现在有", container.get_child_count(), "个子节点")
	
	# 如果是玩家单位，连接战场信号
	if is_player:
		connect_board_card_signals(card)

func log_message(message: String):
	"""添加游戏日志"""
	if game_log:
		game_log.append_text(message + "\n")
		# 确保滚动到底部显示最新日志
		await get_tree().process_frame  # 等待一帧确保内容已更新
		var scroll_container = game_log.get_parent() as ScrollContainer
		if scroll_container:
			scroll_container.scroll_vertical = scroll_container.get_v_scroll_bar().max_value

func _on_start_button_pressed():
	"""开始游戏按钮"""
	start_new_game()

func _on_settings_button_pressed():
	"""设置按钮"""
	show_settings()

func _on_quit_button_pressed():
	"""退出游戏按钮"""
	get_tree().quit()

func _on_end_turn_button_pressed():
	"""结束回合按钮"""
	if is_game_active and GameManager:
		# 播放结束回合音效
		play_end_turn_sound()
		
		# 添加战场伤害结算提示
		if GameManager.player_board.size() > 0 or GameManager.ai_board.size() > 0:
			log_message("[color=orange]⚔️ 回合结束，开始战场伤害结算...[/color]")
		
		GameManager.end_turn()



func _on_game_started():
	"""游戏开始回调"""
	log_message("[color=green]游戏已开始！[/color]")
	print("Main: 收到游戏开始信号，开始更新显示")
	update_all_displays()
	
	# 添加调试信息
	await get_tree().create_timer(0.5).timeout
	debug_card_visibility()

func _on_turn_changed(player_type):
	"""回合变化回调"""
	if player_type == GameManager.PlayerType.PLAYER:
		turn_label.text = "玩家回合"
		turn_label.modulate = Color.GREEN
		end_turn_button.disabled = false
		log_message("[color=green]轮到你了！[/color]")
	else:
		turn_label.text = "AI回合"
		turn_label.modulate = Color.RED
		end_turn_button.disabled = true
		log_message("[color=red]AI正在行动...[/color]")
	
	update_all_displays()

func _on_game_ended(winner):
	"""游戏结束回调"""
	is_game_active = false
	end_turn_button.disabled = true
	
	if winner == GameManager.PlayerType.PLAYER:
		log_message("[color=gold]恭喜你获得胜利！[/color]")
		turn_label.text = "玩家胜利！"
		turn_label.modulate = Color.GOLD
		# 延迟显示胜利界面
		await get_tree().create_timer(1.5).timeout
		game_over_screen.show_victory()
	else:
		log_message("[color=red]很遗憾，你失败了...[/color]")
		turn_label.text = "AI胜利！"
		turn_label.modulate = Color.RED
		# 延迟显示失败界面
		await get_tree().create_timer(1.5).timeout
		game_over_screen.show_defeat()

func _on_health_changed(player_type, new_health: int):
	"""生命值变化回调"""
	print("Main: 收到生命值变化信号 - 玩家类型: ", player_type, " 新生命值: ", new_health)
	
	if player_type == GameManager.PlayerType.PLAYER:
		player_health_label.text = "玩家生命值: " + str(new_health)
		if new_health <= 10:
			player_health_label.modulate = Color.RED
		else:
			player_health_label.modulate = Color.GREEN
	else:
		ai_health_label.text = "AI生命值: " + str(new_health)
		if new_health <= 10:
			ai_health_label.modulate = Color.RED
		else:
			ai_health_label.modulate = Color.GREEN  # 修复：AI生命值高时应该是绿色

func _on_mana_changed(player_type, new_mana: int, max_mana: int):
	"""法力值变化回调"""
	if player_type == GameManager.PlayerType.PLAYER:
		player_mana_label.text = "玩家法力: " + str(new_mana) + "/" + str(max_mana)
		# 只更新手牌可打出状态，不重建UI
		update_playable_cards_ui()
	else:
		ai_mana_label.text = "AI法力: " + str(new_mana) + "/" + str(max_mana)

func _on_card_played(card: Control, player_type):
	"""卡牌被打出回调"""
	var player_name = "玩家" if player_type == GameManager.PlayerType.PLAYER else "AI"
	log_message("[color=cyan]" + player_name + " 打出了: " + card.card_name + "[/color]")
	
	# 播放出牌音效
	play_card_sound()
	
	# 如果是玩家的卡牌，需要从手牌容器中移除
	if player_type == GameManager.PlayerType.PLAYER and card.get_parent() == player_hand_container:
		player_hand_container.remove_child(card)
		print("Main: 从手牌容器移除卡牌: ", card.card_name)
	
	# 更新显示
	update_all_displays()

func _on_unit_attacked(attacker: Control, target, player_type):
	"""单位攻击回调"""
	var player_name = "玩家" if player_type == GameManager.PlayerType.PLAYER else "AI"
	var target_name = "英雄" if target == null else target.card_name
	
	log_message("[color=orange]" + player_name + "的 " + attacker.card_name + " 攻击了 " + target_name + "[/color]")
	
	# 更新显示
	update_all_displays()

func _on_card_clicked(card: Control):
	"""手牌卡牌被点击"""
	print("Main: _on_card_clicked 被调用 - 卡牌: ", card.card_name if card else "null")
	print("Main: is_game_active = ", is_game_active)
	print("Main: GameManager.current_state = ", GameManager.current_state if GameManager else "GameManager为null")
	print("Main: GameManager.GameState.PLAYER_TURN = ", GameManager.GameState.PLAYER_TURN if GameManager else "GameManager为null")
	
	if not is_game_active or GameManager.current_state != GameManager.GameState.PLAYER_TURN:
		print("Main: 卡牌点击被阻止 - 游戏未激活或不是玩家回合")
		return
	
	if card.is_in_hand:
		print("Main: 卡牌在手牌中，尝试打出")
		# 尝试打出卡牌
		if GameManager.can_play_card(card, GameManager.PlayerType.PLAYER):
			print("Main: 可以打出卡牌，调用GameManager.play_card")
			GameManager.play_card(card, GameManager.PlayerType.PLAYER)
		else:
			print("Main: 无法打出卡牌")
			log_message("[color=red]无法打出: " + card.card_name + "（法力不足或其他限制）[/color]")
	else:
		print("Main: 卡牌不在手牌中，is_in_hand = ", card.is_in_hand)

func _on_board_card_clicked(card: Control):
	"""战场卡牌被点击"""
	if not is_game_active or GameManager.current_state != GameManager.GameState.PLAYER_TURN:
		return
	
	if card.is_on_board and not card.has_attacked_this_turn and not card.has_summoning_sickness:
		# 选择攻击目标
		selected_card = card
		log_message("[color=yellow]选择了 " + card.card_name + "，点击目标进行攻击[/color]")
		# 这里可以添加视觉反馈，比如高亮选中的卡牌
		card.modulate = Color.YELLOW

func _on_card_drag_started(card: Control):
	"""卡牌开始拖拽"""
	is_dragging_card = true
	selected_card = card
	log_message("[color=gray]开始拖拽: " + card.card_name + "[/color]")

func _on_card_drag_ended(card: Control, dropped_on_board: bool):
	"""卡牌结束拖拽"""
	print("Main: 卡牌拖拽结束 - ", card.card_name, ", 是否拖到战场: ", dropped_on_board)
	is_dragging_card = false
	selected_card = null
	
	# 如果拖拽到了战场区域，尝试打出卡牌
	if dropped_on_board and GameManager and GameManager.current_state == GameManager.GameState.PLAYER_TURN:
		if GameManager.can_play_card(card, GameManager.PlayerType.PLAYER):
			print("Main: 可以打出卡牌，调用GameManager.play_card")
			GameManager.play_card(card, GameManager.PlayerType.PLAYER)
			log_message("[color=green]打出卡牌: " + card.card_name + "[/color]")
		else:
			print("Main: 无法打出卡牌，原因可能是法力不足")
			log_message("[color=red]无法打出: " + card.card_name + "（法力不足或其他限制）[/color]")
			# 卡牌返回手牌
			card.return_to_hand()
	else:
		card.return_to_hand()

func _on_card_played_by_drag(card: Control):
	"""通过拖拽打出卡牌"""
	if GameManager and GameManager.current_state == GameManager.GameState.PLAYER_TURN:
		GameManager.play_card(card, GameManager.PlayerType.PLAYER)

func update_all_displays():
	"""更新所有显示"""
	# update_player_hand() # 注释掉，避免重复调用
	update_player_board()
	update_ai_board()
	
	# 更新生命值和法力值显示
	if GameManager:
		# 更新玩家信息
		player_health_label.text = "玩家生命值: " + str(GameManager.player_health)
		player_mana_label.text = "玩家法力: " + str(GameManager.player_mana) + "/" + str(GameManager.player_max_mana)
		
		# 更新AI信息
		ai_health_label.text = "AI生命值: " + str(GameManager.ai_health)
		ai_mana_label.text = "AI法力: " + str(GameManager.ai_mana) + "/" + str(GameManager.ai_max_mana)
		
		# 设置生命值颜色
		if GameManager.player_health <= 10:
			player_health_label.modulate = Color.RED
		else:
			player_health_label.modulate = Color.GREEN
			
		if GameManager.ai_health <= 10:
			ai_health_label.modulate = Color.RED
		else:
			ai_health_label.modulate = Color.GREEN
		


func _test_drag_functionality():
	"""测试拖动功能"""
	print("=== 开始测试拖动功能 ===")
	
	# 检查游戏是否已开始
	if not is_game_active:
		print("游戏未开始，先开始游戏")
		start_new_game()
		await get_tree().create_timer(2.0).timeout
	
	# 给玩家足够的法力进行测试
	if GameManager:
		GameManager.player_mana = 10
		GameManager.player_max_mana = 10
		print("设置玩家法力为10用于测试")
	
	# 获取第一张手牌
	if player_hand_container and player_hand_container.get_child_count() > 0:
		var card = player_hand_container.get_child(0)
		print("测试卡牌: ", card.card_name)
		print("卡牌费用: ", card.cost)
		print("玩家法力: ", GameManager.player_mana, "/", GameManager.player_max_mana)
		
		# 检查是否可以打出
		var can_play = GameManager.can_play_card(card, GameManager.PlayerType.PLAYER)
		print("是否可以打出: ", can_play)
		
		if can_play:
			# 模拟拖动到战场
			print("模拟拖动卡牌到战场...")
			_on_card_drag_ended(card, true)
			
			# 等待一帧让事件处理完成
			#await get_tree().process_frame
			
			# 检查结果
			print("检查拖动结果:")
			print("  玩家战场卡牌数量: ", GameManager.player_board.size())
			print("  手牌容器子节点数量: ", player_hand_container.get_child_count())
			print("  战场容器子节点数量: ", player_board_container.get_child_count())
		else:
			print("无法打出卡牌，可能是法力不足")
	else:
		print("没有找到手牌")
	
	print("=== 测试完成 ===")



func _on_ai_board_clicked():
	"""AI战场被点击（用于攻击）"""
	if selected_card and selected_card.is_on_board:
		# 攻击AI英雄
		GameManager.attack_with_unit(selected_card, null, GameManager.PlayerType.PLAYER)
		# 取消选择
		selected_card.modulate = Color.WHITE
		selected_card = null

func _on_ai_unit_clicked(target_card: Control):
	"""AI单位被点击（用于攻击）"""
	if selected_card and selected_card.is_on_board:
		# 攻击AI单位
		GameManager.attack_with_unit(selected_card, target_card, GameManager.PlayerType.PLAYER)
		# 取消选择
		selected_card.modulate = Color.WHITE
		selected_card = null

# 调试功能
func _on_debug_button_pressed():
	"""调试按钮（可选）"""
	if GameManager:
		var state = GameManager.get_game_state()
		print("游戏状态: ", state)
		log_message("[color=gray]调试信息已输出到控制台[/color]")

func show_card_tooltip(card: Control, position: Vector2):
	"""显示卡牌提示（未来功能）"""
	pass

func debug_card_visibility():
	"""调试卡牌可见性"""
	print("=== 开始调试卡牌可见性 ===")
	
	# 检查手牌容器
	if player_hand_container:
		print("手牌容器存在: ", player_hand_container.name)
		print("手牌容器位置: ", player_hand_container.global_position)
		print("手牌容器大小: ", player_hand_container.size)
		print("手牌容器可见: ", player_hand_container.visible)
		print("手牌容器子节点数量: ", player_hand_container.get_child_count())
		
		# 检查每张卡牌
		for i in range(player_hand_container.get_child_count()):
			var card = player_hand_container.get_child(i)
			print("卡牌 ", i, ": ", card.name)
			print("  位置: ", card.global_position)
			print("  大小: ", card.size)
			print("  可见: ", card.visible)
			print("  模块化: ", card.modulate)
			
			# 检查卡牌的子节点
			for j in range(card.get_child_count()):
				var child = card.get_child(j)
				print("    子节点 ", j, ": ", child.name, " 可见: ", child.visible)
	else:
		print("手牌容器不存在！")
	
	print("=== 调试完成 ===")

# 卡牌提示框相关函数
func _connect_card_tooltip_signals():
	"""连接卡牌提示框相关信号"""
	print("Main: 开始连接卡牌提示框信号...")
	
	# 为手牌容器中的所有卡牌连接信号
	if player_hand_container:
		var cards = player_hand_container.get_children()
		print("Main: 找到 ", cards.size(), " 张卡牌需要连接信号")
		
		for card in cards:
			_connect_card_signals(card)
	else:
		print("Main: ⚠️ 手牌容器未找到，无法连接卡牌信号")

func _connect_card_signals(card: Control):
	"""为单张卡牌连接提示框信号"""
	if card and card.has_signal("card_mouse_entered") and card.has_signal("card_mouse_exited"):
		# 连接鼠标进入和离开信号
		if not card.card_mouse_entered.is_connected(_on_card_mouse_entered):
			card.card_mouse_entered.connect(_on_card_mouse_entered)
		if not card.card_mouse_exited.is_connected(_on_card_mouse_exited):
			card.card_mouse_exited.connect(_on_card_mouse_exited)
		print("Main: 已为卡牌连接提示框信号: ", card.name)

func _on_card_mouse_entered(card: Control):
	"""处理卡牌鼠标进入事件"""
	if card_tooltip and card and game_settings.show_tooltips:
		# 只有在设置中启用了提示框时才显示
		card_tooltip.show_tooltip(card, get_global_mouse_position())

func _on_card_mouse_exited(card: Control):
	"""处理卡牌鼠标离开事件"""
	if card_tooltip:
		# 隐藏提示框
		card_tooltip.hide_tooltip()

func hide_card_tooltip():
	"""隐藏卡牌提示（未来功能）"""
	pass

# ===== 信号管理函数 =====

func disconnect_all_card_signals(card: Control):
	"""断开卡牌的所有信号连接"""
	if not is_instance_valid(card):
		return
	
	# 断开点击信号
	if card.card_clicked.is_connected(_on_card_clicked):
		card.card_clicked.disconnect(_on_card_clicked)
	if card.card_clicked.is_connected(_on_board_card_clicked):
		card.card_clicked.disconnect(_on_board_card_clicked)
	
	# 断开拖拽信号
	if card.card_drag_started.is_connected(_on_card_drag_started):
		card.card_drag_started.disconnect(_on_card_drag_started)
	if card.card_drag_ended.is_connected(_on_card_drag_ended):
		card.card_drag_ended.disconnect(_on_card_drag_ended)
	if card.card_played.is_connected(_on_card_played_by_drag):
		card.card_played.disconnect(_on_card_played_by_drag)
	
	# 断开提示框信号
	if card.card_mouse_entered.is_connected(_on_card_mouse_entered):
		card.card_mouse_entered.disconnect(_on_card_mouse_entered)
	if card.card_mouse_exited.is_connected(_on_card_mouse_exited):
		card.card_mouse_exited.disconnect(_on_card_mouse_exited)

func connect_hand_card_signals(card: Control):
	"""连接手牌卡牌的信号"""
	if not is_instance_valid(card):
		return
	
	# 先断开所有信号
	disconnect_all_card_signals(card)
	
	# 连接手牌相关信号
	card.card_clicked.connect(_on_card_clicked)
	card.card_drag_started.connect(_on_card_drag_started)
	card.card_drag_ended.connect(_on_card_drag_ended)
	card.card_played.connect(_on_card_played_by_drag)
	
	# 连接提示框信号
	_connect_card_signals(card)

# ===== 游戏结束页面处理函数 =====

func _on_play_again_requested():
	"""处理重新开始请求"""
	print("Main: 收到重新开始请求")
	game_over_screen.hide_screen()
	start_new_game()

func _on_main_menu_requested():
	"""处理返回主菜单请求"""
	print("Main: 收到返回主菜单请求")
	game_over_screen.hide_screen()
	show_menu()

func _test_victory():
	"""测试胜利界面"""
	if is_game_active:
		is_game_active = false
		end_turn_button.disabled = true
		game_over_screen.show_victory()

func _test_defeat():
	"""测试失败界面"""
	if is_game_active:
		is_game_active = false
		end_turn_button.disabled = true
		game_over_screen.show_defeat()

# ===== 设置系统函数 =====

func initialize_settings():
	"""初始化设置系统"""
	print("Main: 初始化设置系统")
	
	# 加载设置
	load_settings()
	
	# 连接设置界面信号
	connect_settings_signals()
	
	# 应用设置到UI
	apply_settings_to_ui()
	
	print("Main: 设置系统初始化完成")

func initialize_background_music():
	"""初始化背景音乐"""
	print("=== BACKGROUND MUSIC INITIALIZATION START ===")
	print("Main: 开始初始化背景音乐")
	
	# 检查背景音乐播放器节点
	print("Main: 检查背景音乐播放器节点...")
	print("Main: background_music_player = ", background_music_player)
	
	if background_music_player:
		print("Main: ✅ 背景音乐播放器节点找到")
		print("Main: 播放器节点名称: ", background_music_player.name)
		
		# 加载背景音乐文件
		print("Main: 尝试加载背景音乐文件...")
		var audio_path = "res://assets/audio/background.mp3"
		print("Main: 音频文件路径: ", audio_path)
		
		var audio_stream = load(audio_path)
		print("Main: 加载结果: ", audio_stream)
		
		if audio_stream:
			print("Main: ✅ 音频文件加载成功")
			print("Main: 音频流类型: ", audio_stream.get_class())
			
			# 设置音频流
			background_music_player.stream = audio_stream
			print("Main: ✅ 音频流已设置")
			
			# 检查音频流的循环设置
			if audio_stream is AudioStreamMP3:
				print("Main: 🔄 音频流循环设置: ", audio_stream.loop)
			else:
				print("Main: ⚠️ 音频流类型不是MP3: ", audio_stream.get_class())
			
			# 设置音量
			background_music_player.volume_db = -10.0
			print("Main: ✅ 音量设置为 -10dB")
			
			# 设置自动播放
			background_music_player.autoplay = true
			print("Main: ✅ 自动播放已启用")
			
			# 设置音频总线
			background_music_player.bus = "Master"
			print("Main: ✅ 音频总线设置为 Master")
			
			# 检查播放状态
			print("Main: 当前播放状态: ", background_music_player.playing)
			
			# 如果音乐没有自动播放，手动播放
			if not background_music_player.playing:
				print("Main: 音乐未自动播放，手动启动...")
				background_music_player.play()
				print("Main: 播放命令已发送")
				
				# 等待一帧后检查状态
				await get_tree().process_frame
				print("Main: 播放后状态: ", background_music_player.playing)
			
			print("Main: ✅ 背景音乐初始化完成")
		else:
			print("Main: ❌ 无法加载背景音乐文件: ", audio_path)
			print("Main: 请检查文件是否存在和格式是否正确")
	else:
		print("Main: ❌ 背景音乐播放器节点未找到")
		print("Main: 请检查Main.tscn中是否正确添加了BackgroundMusicPlayer节点")
	
	print("=== BACKGROUND MUSIC INITIALIZATION END ===")

func play_background_music():
	"""播放背景音乐"""
	if background_music_player and background_music_player.stream:
		background_music_player.play()
		print("Main: 背景音乐开始播放")

func pause_background_music():
	"""暂停背景音乐"""
	if background_music_player and background_music_player.playing:
		background_music_player.stream_paused = true
		print("Main: 背景音乐已暂停")

func resume_background_music():
	"""恢复背景音乐播放"""
	if background_music_player and background_music_player.stream:
		background_music_player.stream_paused = false
		print("Main: 背景音乐恢复播放")

func stop_background_music():
	"""停止背景音乐"""
	if background_music_player and background_music_player.playing:
		background_music_player.stop()
		print("Main: 背景音乐已停止")

func set_background_music_volume(volume_db: float):
	"""设置背景音乐音量"""
	if background_music_player:
		background_music_player.volume_db = volume_db
		print("Main: 背景音乐音量设置为 ", volume_db, " dB")

# ===== 音效播放函数 =====

func play_card_sound():
	"""播放出牌音效"""
	if sound_effect_player and CARD_PLAY_SOUND:
		sound_effect_player.stream = CARD_PLAY_SOUND
		# 根据设置调整音量
		var volume_percent = game_settings.get("sound_effect_volume", 80)
		var volume_db = linear_to_db(volume_percent / 100.0)
		sound_effect_player.volume_db = volume_db
		sound_effect_player.play()
		print("Main: 播放出牌音效，音量: ", volume_percent, "%")

func play_end_turn_sound():
	"""播放结束回合音效"""
	if sound_effect_player and END_TURN_SOUND:
		sound_effect_player.stream = END_TURN_SOUND
		# 根据设置调整音量
		var volume_percent = game_settings.get("sound_effect_volume", 80)
		var volume_db = linear_to_db(volume_percent / 100.0)
		sound_effect_player.volume_db = volume_db
		sound_effect_player.play()
		print("Main: 播放结束回合音效，音量: ", volume_percent, "%")

func set_sound_effect_volume(volume_percent: int):
	"""设置音效音量（百分比）"""
	game_settings["sound_effect_volume"] = volume_percent
	print("Main: 音效音量设置为 ", volume_percent, "%")

func adjust_sound_effect_volume(delta: int):
	"""调节音效音量（增加或减少）"""
	var current_volume = game_settings.get("sound_effect_volume", 80)
	var new_volume = clamp(current_volume + delta, 0, 100)
	
	if new_volume != current_volume:
		set_sound_effect_volume(new_volume)
		# 播放一个测试音效来让玩家听到音量变化
		play_card_sound()
		# 显示音量变化提示
		log_message("[color=cyan]音效音量: " + str(new_volume) + "%[/color]")
		# 保存设置
		save_settings()
	else:
		# 已达到音量极限
		if new_volume == 0:
			log_message("[color=yellow]音效音量已达到最小值[/color]")
		elif new_volume == 100:
			log_message("[color=yellow]音效音量已达到最大值[/color]")

func connect_settings_signals():
	"""连接设置界面的信号"""
	# 连接滑块信号
	master_volume_slider.value_changed.connect(_on_master_volume_changed)
	sfx_volume_slider.value_changed.connect(_on_sfx_volume_changed)
	
	# 连接复选框信号
	auto_end_turn_checkbox.toggled.connect(_on_auto_end_turn_toggled)
	show_tooltips_checkbox.toggled.connect(_on_show_tooltips_toggled)
	
	# 连接按钮信号
	reset_button.pressed.connect(_on_reset_settings_pressed)
	back_button.pressed.connect(_on_settings_back_pressed)

func load_settings():
	"""从文件加载设置"""
	if FileAccess.file_exists(SETTINGS_FILE_PATH):
		var file = FileAccess.open(SETTINGS_FILE_PATH, FileAccess.READ)
		if file:
			var json_string = file.get_as_text()
			file.close()
			
			var json = JSON.new()
			var parse_result = json.parse(json_string)
			if parse_result == OK:
				var loaded_settings = json.data
				# 合并加载的设置到默认设置
				for key in loaded_settings:
					if key in game_settings:
						game_settings[key] = loaded_settings[key]
				print("Main: 设置加载成功")
			else:
				print("Main: 设置文件解析失败")
	else:
		print("Main: 设置文件不存在，使用默认设置")

func save_settings():
	"""保存设置到文件"""
	var file = FileAccess.open(SETTINGS_FILE_PATH, FileAccess.WRITE)
	if file:
		var json_string = JSON.stringify(game_settings)
		file.store_string(json_string)
		file.close()
		print("Main: 设置保存成功")
	else:
		print("Main: 设置保存失败")

func apply_settings_to_ui():
	"""将设置应用到UI界面"""
	# 应用音量设置
	master_volume_slider.value = game_settings.master_volume
	sfx_volume_slider.value = game_settings.sfx_volume
	master_volume_value.text = str(game_settings.master_volume) + "%"
	sfx_volume_value.text = str(game_settings.sfx_volume) + "%"
	
	# 应用游戏设置
	auto_end_turn_checkbox.button_pressed = game_settings.auto_end_turn
	show_tooltips_checkbox.button_pressed = game_settings.show_tooltips
	
	# 应用音量到音频系统
	apply_audio_settings()

func apply_audio_settings():
	"""应用音频设置到音频系统"""
	# 设置主音量
	var master_db = linear_to_db(game_settings.master_volume / 100.0)
	AudioServer.set_bus_volume_db(AudioServer.get_bus_index("Master"), master_db)
	
	# 设置音效音量（如果有SFX总线的话）
	var sfx_bus_index = AudioServer.get_bus_index("SFX")
	if sfx_bus_index != -1:
		var sfx_db = linear_to_db(game_settings.sfx_volume / 100.0)
		AudioServer.set_bus_volume_db(sfx_bus_index, sfx_db)

func show_settings():
	"""显示设置界面"""
	settings_overlay.visible = true
	menu_overlay.visible = false
	log_message("[color=cyan]打开设置界面[/color]")

func hide_settings():
	"""隐藏设置界面"""
	settings_overlay.visible = false
	menu_overlay.visible = true
	log_message("[color=cyan]关闭设置界面[/color]")

func reset_settings_to_default():
	"""重置设置为默认值"""
	game_settings = {
		"master_volume": 80,
		"sfx_volume": 70,
		"auto_end_turn": false,
		"show_tooltips": true
	}
	apply_settings_to_ui()
	save_settings()
	log_message("[color=yellow]设置已重置为默认值[/color]")

# ===== 设置界面信号处理函数 =====

func _on_master_volume_changed(value: float):
	"""主音量滑块变化"""
	game_settings.master_volume = int(value)
	master_volume_value.text = str(int(value)) + "%"
	apply_audio_settings()
	save_settings()

func _on_sfx_volume_changed(value: float):
	"""音效音量滑块变化"""
	game_settings.sfx_volume = int(value)
	sfx_volume_value.text = str(int(value)) + "%"
	apply_audio_settings()
	save_settings()

func _on_auto_end_turn_toggled(pressed: bool):
	"""自动结束回合复选框变化"""
	game_settings.auto_end_turn = pressed
	save_settings()
	if pressed:
		log_message("[color=green]已启用自动结束回合[/color]")
	else:
		log_message("[color=gray]已禁用自动结束回合[/color]")

func _on_show_tooltips_toggled(pressed: bool):
	"""显示卡牌提示复选框状态改变"""
	game_settings.show_tooltips = pressed
	save_settings()
	if pressed:
		log_message("[color=green]已启用卡牌提示[/color]")
	else:
		log_message("[color=gray]已禁用卡牌提示[/color]")

# 获取游戏设置（供其他脚本调用）
func get_game_settings():
	"""返回当前游戏设置"""
	return game_settings

func _on_reset_settings_pressed():
	"""重置设置按钮"""
	reset_settings_to_default()

func _on_settings_back_pressed():
	"""设置界面返回按钮"""
	hide_settings()

func connect_board_card_signals(card: Control):
	"""连接战场卡牌的信号"""
	if not is_instance_valid(card):
		return
	
	# 先断开所有信号
	disconnect_all_card_signals(card)
	
	# 连接战场相关信号
	card.card_clicked.connect(_on_board_card_clicked)
	
	# 连接提示框信号
	_connect_card_signals(card)
